<template>
    <a-drawer
    width="70%"
    title="查看点"
    placement="right"
    :visible="modal_show"
    :maskClosable="false"
    :closable="false"
    :bodyStyle="{ padding: '0px' }"
    :maskStyle="{ display: 'none' }"
    :mask="false"
    :zIndex="1002"
     @afterVisibleChange="afterVisibleChange"
    >
    <template #extra>
        <a-tooltip  placement="bottom">
            <template #title>关闭</template>
            <a-button @click="onClose" style="margin: 0 auto;margin-right: 10px;">
            <template #icon>
                <close-outlined />
            </template>
            </a-button>
        </a-tooltip>
    </template>
        <a-row style="height: 100%;width: 100%;">
            <div id="mapcontainer"  class="map-container" style="height: 100%;width: 100%;"></div>
        </a-row>
    </a-drawer>
    <match_points_detail/>
</template>
<script>
import { defineAsyncComponent, createVNode, toRaw ,h,} from 'vue' 
import { useRoute } from "vue-router"
import { Modal,notification, Button } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import Map from "@arcgis/core/Map.js";
import MapView from "@arcgis/core/views/MapView.js";
import Graphic from "@arcgis/core/Graphic.js";
import Point from "@arcgis/core/geometry/Point.js";

import Circle from "@arcgis/core/geometry/Circle.js";
import GroupLayer from "@arcgis/core/layers/GroupLayer.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
import WebTileLayer from "@arcgis/core/layers/WebTileLayer.js";
import ImageryTileLayer from "@arcgis/core/layers/ImageryTileLayer.js";
import * as geometryEngine from "@arcgis/core/geometry/geometryEngine.js";
import * as projection from "@arcgis/core/geometry/projection.js";
import * as rasterFunctionUtils from "@arcgis/core/layers/support/rasterFunctionUtils.js";
import Draw from "@arcgis/core/views/draw/Draw.js";
import Swipe from "@arcgis/core/widgets/Swipe.js";
import esriConfig from "@arcgis/core/config.js";
esriConfig.assetsPath = "./assets";
esriConfig.workers.workerPath = "./assets/esri/core/workers/RemoteClient.js";
let ag_view;//view
let ag_point_layer;//匹配点的layer
let ag_point_highlight_layer;//匹配点高亮的layer
let tif_group;//tif图层集合
export default {
    data() {
        return {
            modal_show:false,
            xml_type:{},
            point_show_type:"",////API查询的匹配点类型
            match_points_result:[],//API查询的xml匹配点
            map_operation_type:"match_point", //当前地图的操作类型

            //mitt
            mitt_calibration_point_id:"",
            mitt_calibration_point_back_id:"",
        };
    },
    async mounted() {
        console.log("calibration_point mounted")
        this.mitt_calibration_point_id=this.$mitt.on('match_point', async (uid,data_obejct) => {
            this.mitt_calibration_point_back_id=uid
            this.modal_show=true
            this.xml_type=data_obejct
            this.point_show_type="";
            console.log("match_point",this.xml_type)
            setTimeout(async()=>{
                
                
            },800)
        });
    },
    beforeUnmount() {
        this.$mitt.off('match_point',this.mitt_calibration_point_id);
        if(ag_view){
            ag_view?.destroy()
            ag_view=undefined
        }
    },  
    components: {
        match_points_detail: defineAsyncComponent(() => import('@/components/task/match_points_detail.vue')),
    },
    methods: {
        onClose(){
            this.modal_show=false
        },
        async afterVisibleChange(visible){
            console.log(`visible is ${visible}`)
            if(visible==true){
                console.log("visibled")
                await this.get_match_points()
                await this.initmap(); //初始化地图
                await this.ad_point(); 
                // this.initmap(); //初始化地图
            }
        },
        //初始化底图控件
        async initmap() {
            //view
            ag_view = new MapView({
                extent: {
                    spatialReference: {
                        wkid: 3857
                    },
                    xmin:  -20037508.342789244,
                    ymin:  -20037508.342789244,
                    xmax: 20037508.342789244,
                    ymax: 20037508.342789244
                },
                center:[0,0],
                ui: {
                    components: []
                },
                zoom:12,
                // navigation: {
                //     gamepad: {
                //         enabled: false
                //     },
                //     browserTouchPanEnabled: false,
                //     momentumEnabled: false,
                //     mouseWheelZoomEnabled: false,
                // }
            });
            var vec_tiandituLayer = new WebTileLayer(`${this.$store.state.true_address}/ser/tdt?layer=vec_w&layername=vec&level={z}&row={y}&col={x}`, {
                title: "天地图-矢量",
                tileInfo: this.$store.state.tileInfo_3857,
                spatialReference: {
                    wkid: 3857
                },
            });
            //匹配点的layer
            ag_point_layer = new FeatureLayer({
                objectIdField: "OBJECTID",
                geometryType: "point",
                fields: [
                    {
                        name: "OBJECTID",
                        type: "oid"
                    },
                    {
                        name: "imagecount",
                        type: "string"
                    }, {
                        name: "type",
                        type: "string"
                    }, {
                        name: "name",
                        type: "string"
                    }, {
                        name: "title",
                        type: "string"
                    }, {
                        name: "fc_type",
                        type: "string"
                    }
                ],
                source: [],
                spatialReference: { wkid: 3857 },
                renderer:{
                    type: "simple",
                    symbol: {
                        type: "simple-marker",
                        outline: null,
                        size:3.5,
                        color:"#0f6f3b",
                    },
                    visualVariables: [
                        {
                            type: "size",
                            field: "imagecount",
                            stops: [
                                { value: 1, size: 3.5 },
                                { value: 10, size: 6 }
                            ],
                        },
                        {
                            type: "color",
                            field: "type",
                            stops: [
                                { value: 0, color: "#0f6f3b" }, 
                                { value: 1, color: "#9b0ac8" }, 
                                { value: 2, color: "#11dc11" }, 
                                { value: 3, color: "#ec8b06" }, 
                                { value: 4, color: "#f1b712" }, 
                                { value: 5, color: "#3185d2" }, 
                            ]
                        },
                        // {
                        //     type: "opacity",
                        //     field: "type",
                        //     stops: [
                        //         { value: 0, opacity: 1 }, 
                        //         { value: 1, opacity: 1 }, 
                        //         { value: 2, opacity: 1 }, 
                        //         { value: 3, opacity: 1 }, 
                        //         { value: 4, opacity: 1 }, 
                        //         { value: 5, opacity: 1 }, 
                        //     ]
                        // },
                    ]
                }
            });
            //匹配点高亮的layer
            ag_point_highlight_layer = new FeatureLayer({
                objectIdField: "OBJECTID",
                geometryType: "point",
                fields: [
                    {
                        name: "OBJECTID",
                        type: "oid"
                    }
                ],
                source: [],
                spatialReference: { wkid: 3857 },
                renderer:{
                    type: "simple",
                    symbol: {
                        type: "simple-marker",
                        color: "red",
                        size: 10,
                        outline: null
                    },
                    
                }
            });
            tif_group=new GroupLayer({
                layers:[],
            })
            let ag_map=new Map({
                basemap:{
                    baseLayers: [
                        vec_tiandituLayer
                    ],
                },
                layers: [tif_group,ag_point_layer, ag_point_highlight_layer]
            });
            ag_view.map = ag_map
            ag_view.container = "mapcontainer"
            //map_operation_type:draw_geom match_process match_point
            ag_view.on("click", (event) => {
                const screenPoint = { x: event.x, y: event.y }; // 获取地图中的地理坐标 
                const mapPoint = ag_view.toMap(screenPoint); 
                console.log(mapPoint)
                ag_view.hitTest(event, { include: [ag_point_layer]}).then( async (response)=> {
                    console.log(response)
                    // let ag_fc_highlight_oid="";
                    // if (response?.results?.length){
                    //     for (let i = 0; i < response?.results?.length; i++) {
                    //         let element = response?.results[i];
                    //         ag_fc_highlight_oid = element?.graphic?.attributes?.OBJECTID
                    //     }
                    // }
                    // this.highlight_Feature_by_id(ag_fc_highlight_oid)
                });
                // // console.log("click",event)
                // if(this.map_operation_type=='draw_geom'){//do nothing

                // }
                // else if(this.map_operation_type=='match_point'){
                
                // }
                // else{
                //     let map_point = ag_view.toMap(event)
                //     this.map_xyz.x = map_point?.x?.toFixed(4)
                //     this.map_xyz.y = map_point?.y?.toFixed(4)
                // }
            });
            ag_view.on("double-click", (event)=> {
                if(this.map_operation_type=='match_point'){
                    ag_view.hitTest(event, { include: [ag_point_layer] }).then(async (response) => {
                        if (response?.results?.length==1) {
                            let dc_fc=response?.results[0]?.graphic
                            this.details_match_point(dc_fc)
                        }
                        else{
                            this.details_match_point()
                        }
                    });
                    event.stopPropagation()
                }

                // //当开始勾画时不执行hitTest
                // //显示匹配进度 双击操作
                // if(this.map_operation_type=='draw_geom'){//do nothing
                // }
                // else if(this.map_operation_type=='match_process'){
                //     ag_view.hitTest(event, { include: [ag_process_layer] }).then(async (response) => {
                //         if (response?.results?.length == 1) {
                //             this.show_process_point(response?.results[0]?.graphic?.attributes)
                //         }
                //     });
                //     event.stopPropagation()
                // }
                // else 
            });
            // 获取鼠标位置的坐标 
            // ag_view.on("pointer-move", function(event) { 
            //     const screenPoint = { x: event.x, y: event.y }; // 获取地图中的地理坐标 
            //     const mapPoint = ag_view.toMap(screenPoint); 
            //     console.log(mapPoint)
            // });
            let dddd=await ag_view.when()
            console.log(dddd)
            // await ag_view.whenLayerView()
            return true
        },
        //查询任务病初始化tree
        async get_match_points() {
            this.$Loading.start();
            this.match_points_result=[]
            this.match_points_result=await this.$apis.get_match_point(this.xml_type)
            this.point_show_type=this.match_points_result?.type
            console.log(this.match_points_result)
            this.$Loading.done();
            return
        },
        async ad_point(){
            await this.clear_featruelayer(ag_point_layer)
            if(this.point_show_type=="ctr"){
                await this.ad_point_to_map_ctr()
            }
            else if(this.point_show_type=="tie"){
                await this.ad_point_to_map_tie()
            }
            else if(this.point_show_type=="multi"){
                await this.ad_point_to_map_multi()
            }
        },
        async ad_point_to_map_ctr(){
            let features = [];
            let minx=1000000;
            let maxx=0;
            let miny=1000000;
            let maxy=-1000000;
            for (let i = 0; i < this.match_points_result?.points.length; i++) {
                let one_point = this.match_points_result?.points[i];
                let one_point_name=one_point?.name;
                let ctr_points=one_point?.points;
                if(ctr_points?.length==2){
                    let one_ctr_point = ctr_points[0];
                    let x=one_ctr_point?.x-0;
                    let y=-(one_ctr_point?.y-0);
                    features.push(new Graphic({
                        geometry: new Point({
                            x: x,
                            y: y,
                            spatialReference: { wkid: 3857 },
                        }),
                        attributes:{
                            name: one_point_name,
                            type:0,
                            imagecount:3
                        },
                    }))
                    if(minx>x){
                        minx=x
                    }
                    if(maxx<x){
                        maxx=x
                    }
                    if(miny>y){
                        miny=y
                    }
                    if(maxy<y){
                        maxy=y
                    }
                }
            }
            console.log(minx,maxx,miny,maxy)
            if (features?.length) {
                console.log(`add ${features.length} features`);
                await ag_point_layer.applyEdits({
                    addFeatures: features
                });
                console.log(ag_point_layer?.fullExtent)
            }
            ag_view.goTo(new Point({
                x: (minx+maxx)/2,
                y: (miny+maxy)/2,
                spatialReference: { wkid: 3857 },
            }))
            tif_group.removeAll()
            let tif_tiled_layer = this.get_WebTileLayer(this.match_points_result?.tif_name, this.match_points_result?.tif)
            tif_group.add(tif_tiled_layer)
        },
        async ad_point_to_map_tie(){
            let features = [];
            let minx=1000000;
            let maxx=0;
            let miny=1000000;
            let maxy=-1000000;
            for (let i = 0; i < this.match_points_result?.points.length; i++) {
                let one_point = this.match_points_result?.points[i];
                let one_point_name=one_point?.name;
                let tie_points=one_point?.points;
                for (let j = 0; j < tie_points?.length; j++) {
                    let one_tie_point = tie_points[j];
                    let x=one_tie_point?.x-0;
                    let y=-(one_tie_point?.y-0);
                    features.push(new Graphic({
                        geometry: new Point({
                            x: x,
                            y: y,
                            spatialReference: { wkid: 3857 },
                        }),
                        attributes:{
                            name: one_point_name,
                            type:j==0?0:1,
                            imagecount:3
                        },
                        
                    }))
                    if(minx>x){
                        minx=x
                    }
                    if(maxx<x){
                        maxx=x
                    }
                    if(miny>y){
                        miny=y
                    }
                    if(maxy<y){
                        maxy=y
                    }
                }
            }
            console.log(minx,maxx,miny,maxy)
            if (features?.length) {
                console.log(`add ${features.length} features`);
                await ag_point_layer.applyEdits({
                    addFeatures: features
                });
                console.log(ag_point_layer?.fullExtent)
            }
            ag_view.goTo(new Point({
                x: (minx+maxx)/2,
                y: (miny+maxy)/2,
                spatialReference: { wkid: 3857 },
            }))
            tif_group.removeAll()
            let tif_tiled_layer = this.get_WebTileLayer(this.match_points_result?.tif_name, this.match_points_result?.tif)
            tif_group.add(tif_tiled_layer)
        },
        async ad_point_to_map_multi(){
            let features = [];
            let minx=1000000;
            let maxx=0;
            let miny=1000000;
            let maxy=-1000000;
            for (let i = 0; i < this.match_points_result?.points.length; i++) {
                let one_point = this.match_points_result?.points[i];
                let one_point_name=one_point?.name;
                let x=0
                let y=0
                if(one_point?.num>0){
                    x=one_point?.points[0]?.x-0;
                    y=-(one_point?.points[0]?.y-0);
                }
                features.push(new Graphic({
                    geometry: new Point({
                        x: x,
                        y: y,
                        spatialReference: { wkid: 3857 },
                    }),
                    attributes:{
                        name: one_point_name,
                        type:0,
                        imagecount:one_point?.num-0
                    },
                }))
                if(minx>x){
                    minx=x
                }
                if(maxx<x){
                    maxx=x
                }
                if(miny>y){
                    miny=y
                }
                if(maxy<y){
                    maxy=y
                }
            }
            console.log(minx,maxx,miny,maxy)
            if (features?.length) {
                console.log(`add ${features.length} features`);
                await ag_point_layer.applyEdits({
                    addFeatures: features
                });
                console.log(ag_point_layer?.fullExtent)
            }
            ag_view.goTo(new Point({
                x: (minx+maxx)/2,
                y: (miny+maxy)/2,
                spatialReference: { wkid: 3857 },
            }))
            tif_group.removeAll()
            // let tif_tiled_layer = this.get_WebTileLayer(this.match_points_result?.tif_name, this.match_points_result?.tif)
            // tif_group.add(tif_tiled_layer)
        },
        get_WebTileLayer(tif_name, layer_tif,layer_fullExtent) {
            let properties={
                urlTemplate: `${this.$store.state.true_address}/ser/tile?layer=${layer_tif}&tilematrix={z}&tilerow={y}&tilecol={x}&in_wkid=3857&out_wkid=3857`,
                spatialReference: {
                    wkid: 3857
                },
                visible: true,
                id: tif_name,
                title: layer_tif,
                copyright: '',
                tileInfo: this.$store.state.tileInfo_3857,
            }
            // if(layer_fullExtent){
            //     properties.fullExtent={
            //         xmin:layer_fullExtent[0],
            //         xmax:layer_fullExtent[1],
            //         ymin:layer_fullExtent[2],
            //         ymax:layer_fullExtent[3],
            //     }
            // }
            return new WebTileLayer(properties);
        },
        //查询任务病初始化tree
        async get_ddom_tif(lon,lat) {
            let tif_result=await this.$apis.get_ddom_tif({
                task_dir :this.$store.state.task_dir,
                task_name:this.$store.state.task.task_name,
                lon,
                lat
            })
            console.log(tif_result)
            return tif_result
        },
        //双击匹配点时显示点的匹配影像详细信息
        async details_match_point(dc_fc){
            let show_point_details=[]
            //1 先清空ag_point_highlight_layer
            await this.clear_featruelayer(ag_point_highlight_layer)
            if(dc_fc){
                //2 再把双击的匹配点显示到ag_point_highlight_layer
                {
                    //由于double-click事件触发的dc_fc的attributes只包含OBJECTID属性
                    //因此需要先查询dc_fc的属性
                    let first_results=await ag_point_layer.queryFeatures({
                        where:`${ag_point_layer.objectIdField} = ${dc_fc?.attributes?.OBJECTID}`
                    })
                    if(first_results?.features?.length!=1){
                        return
                    }
                    let first_dc_fc=first_results?.features[0]
                    let first_dc_fc_name=first_dc_fc?.attributes?.name
                    //从match_points_result中寻找对应的points
                    let first_dc_fc_index=this.match_points_result?.points?.findIndex((val)=>{
                        return val?.name==first_dc_fc_name
                    })
                    if(first_dc_fc_index<0){
                        return
                    }
                    let same_name_points=this.match_points_result?.points[first_dc_fc_index]?.points
                    let highlight_features = [];
                    if(this.point_show_type=="tie"){
                        
                        for (let j = 0; j < same_name_points?.length; j++) {
                            let one_tie_point = same_name_points[j];
                            let x=one_tie_point?.x-0;
                            let y=-(one_tie_point?.y-0);
                            highlight_features.push(new Graphic({
                                geometry: new Point({
                                    x: x,
                                    y: y,
                                    spatialReference: { wkid: 3857 },
                                }),
                            }))
                            show_point_details.push({
                                tif:this.match_points_result?.tif,
                                tif_name:this.match_points_result?.tif_name,
                                in_wkid:3857,
                                out_wkid:3857,
                                point_name:first_dc_fc_name,
                                x:x,
                                y:y,
                            })
                        }
                    }
                    else if(this.point_show_type=="ctr"){
                        let first_x=0;
                        let first_y=0;
                        for (let j = 0; j < same_name_points?.length; j++) {
                            let one_tie_point = same_name_points[j];
                            let x=one_tie_point?.x-0;
                            let y=-(one_tie_point?.y-0);
                            if(j==0){
                                highlight_features.push(new Graphic({
                                    geometry: new Point({
                                        x: x,
                                        y: y,
                                        spatialReference: { wkid: 3857 },
                                    }),
                                }))
                                first_x=one_tie_point?.x
                                first_y=one_tie_point?.y
                            }
                            let tif=this.match_points_result?.tif
                            let tif_name=this.match_points_result?.tif_name
                            if(j==1){
                                tif=this.match_points_result?.sim
                                tif_name=this.match_points_result?.sim_name
                            }
                            show_point_details.push({
                                tif:tif,
                                tif_name:tif_name,
                                in_wkid:3857,
                                out_wkid:3857,
                                point_name:first_dc_fc_name,
                                x:x,
                                y:y,
                            })
                        }
                        if(this.match_points_result?.gcp_points?.length>0){
                            let find_index_gcp=this.match_points_result?.gcp_points?.findIndex((val)=>{
                                return (val?.x==first_x) && (val?.y==first_y)
                            })
                            if(find_index_gcp>=0){
                                let gcp_point=this.match_points_result?.gcp_points[find_index_gcp]
                                let gcp_lon=gcp_point?.lon-0
                                let gcp_lat=gcp_point?.lat-0
                                let dom_tif=await this.get_ddom_tif(gcp_lon,gcp_lat)
                                if(dom_tif){
                                    show_point_details.push({
                                        tif:dom_tif,
                                        tif_name:dom_tif,
                                        in_wkid:4326,
                                        out_wkid:4326,
                                        point_name:first_dc_fc_name,
                                        x:gcp_lon,
                                        y:gcp_lat,
                                    })
                                }
                            }
                            
                        }
                        
                    }
                    else if(this.point_show_type=="multi"){
                        for (let j = 0; j < same_name_points?.length; j++) {
                            let one_tie_point = same_name_points[j];
                            let x=one_tie_point?.x-0;
                            let y=-(one_tie_point?.y-0);
                            if(j==0){
                                highlight_features.push(new Graphic({
                                    geometry: new Point({
                                        x: x,
                                        y: y,
                                        spatialReference: { wkid: 3857 },
                                    }),
                                }))
                            }
                            let tif_i=one_tie_point?.i-0;
                            let tif_index=this.match_points_result?.tifs?.findIndex((val)=>{
                                return val?.i==tif_i
                            })
                            if(tif_index>=0){
                                show_point_details.push({
                                    tif:this.match_points_result?.tifs[tif_index]?.tif,
                                    tif_name:this.match_points_result?.tifs[tif_index]?.tif_name,
                                    in_wkid:3857,
                                    out_wkid:3857,
                                    point_name:first_dc_fc_name,
                                    x:x,
                                    y:y,
                                })
                            }
                        }
                    }
                    if (highlight_features?.length) {
                        await ag_point_highlight_layer.applyEdits({
                            addFeatures: highlight_features
                        });
                    }
                }
                //3 显示详细的点
                this.$mitt.iemit('match_points_detail', show_point_details,this?.$?.uid);
            }
        },
        //clear_featruelayer 传入的参数是layer
        async clear_featruelayer(layer) {
            let fc_ids = await layer.queryObjectIds()
            if (fc_ids?.length){
                let deleteFeatures = []
                for (let i = 0; i < fc_ids?.length; i++) {
                    deleteFeatures.push({
                        objectId: fc_ids[i]
                    })
                }
                await layer.applyEdits({
                    deleteFeatures: deleteFeatures
                });
            }
            return true
        },
    },
}
</script>
<style>
@import url('~@arcgis/core/assets/esri/themes/light/main.css');
.esri-view-surface--inset-outline:focus::after {
    outline: none !important;
}
.esri-swipe__container:focus .esri-swipe__handle,
.esri-swipe__container:focus .esri-swipe__divider {
    outline: none !important;
}
.esri-view {
    --esri-view-outline: 0px solid var(--esri-view-outline-color);
    --esri-view-outline-offset: 0px;
}
*,
*:before,
*:after {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}
</style>